# Dockerfile for Next.js app in a pnpm monorepo
# This Dockerfile should be built from the root of the monorepo:
# > docker build -t iris-ssr .
# > docker run -p 3000:3000 iris-ssr

# -----------------
# Base stage
# -----------------
FROM node:20-alpine AS base
WORKDIR /app
RUN corepack enable
RUN sed -i 's#https\?://dl-cdn.alpinelinux.org/alpine#http://mirrors.tuna.tsinghua.edu.cn/alpine#g' /etc/apk/repositories


# -----------------
# Builder stage
# -----------------
FROM base AS builder

RUN apk update && apk add --no-cache git perl
# 克隆 Afilmory 仓库 并安装依赖 注意此时版本 提交号为 f13adda79574e596f5fecbe907f1f48688966874
# RUN git clone https://github.com/Afilmory/Afilmory --depth 1 .

RUN git clone https://gitee.com/snowyan/afilmory.git --branch release-251103 --depth 1 .
COPY config.json ./
COPY builder.config.ts ./
COPY .env ./

ARG S3_ACCESS_KEY_ID
ARG S3_SECRET_ACCESS_KEY
ARG GIT_TOKEN
ARG PG_CONNECTION_STRING

# 将 ARG 转换为 ENV，以便构建过程可以使用这些变量
ENV S3_ACCESS_KEY_ID=${S3_ACCESS_KEY_ID}
ENV S3_SECRET_ACCESS_KEY=${S3_SECRET_ACCESS_KEY}
ENV GIT_TOKEN=${GIT_TOKEN}
ENV PG_CONNECTION_STRING=${PG_CONNECTION_STRING}

# 创建一个脚本来加载 .env 文件并执行命令
# 这样可以确保构建时能够读取 .env 文件中的环境变量
RUN echo '#!/bin/sh' > /usr/local/bin/load-env.sh && \
    echo 'set -a' >> /usr/local/bin/load-env.sh && \
    echo '[ -f .env ] && . .env' >> /usr/local/bin/load-env.sh && \
    echo 'set +a' >> /usr/local/bin/load-env.sh && \
    echo 'exec "$@"' >> /usr/local/bin/load-env.sh && \
    chmod +x /usr/local/bin/load-env.sh

RUN sh ./scripts/preinstall.sh
# Install all dependencies
RUN  pnpm config set registry https://mirrors.huaweicloud.com/repository/npm/ \
 && pnpm install --frozen-lockfile

# Build the app.
# The build script in the ssr package.json handles building the web app first.
# 使用 load-env.sh 脚本加载 .env 文件中的环境变量，然后执行构建
RUN /usr/local/bin/load-env.sh pnpm --filter=@afilmory/ssr build

# -----------------
# Runner stage
# -----------------
FROM base AS runner

WORKDIR /app

ENV NODE_ENV=production
# ENV PORT and other configurations are now in the config files
# and passed through environment variables during runtime.
RUN apk add --no-cache curl wget
# Create a non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

USER nextjs

COPY --from=builder --chown=nextjs:nodejs /app/apps/ssr/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/ssr/.next/static /app/apps/ssr/.next/static
COPY --from=builder --chown=nexts:nodejs /app/apps/ssr/public /app/apps/ssr/public
COPY --from=builder --chown=nextjs:nodejs /app/apps/ssr/public /app/apps/ssr/public/static/web

# The standalone output includes the server.js file.
# The PORT environment variable is automatically used by Next.js.
EXPOSE 3000

CMD ["node", "apps/ssr/server.js"]
